﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Mani.Patient.Business.Services;
using Mani.Common;
using Mani.Patient.Business.Domain.Entity;
using System.Collections.Generic;

public partial class PatientInfo : System.Web.UI.Page {

    public IPatientService PatientService { get; set; }
    public IQuestionService QuestionService { get; set; }

    protected override void InitializeCulture() {
        MyCulture.SetCulture();
        base.InitializeCulture();
    }
    
    protected void Page_Load(object sender, EventArgs e) {
        if (!Page.IsPostBack) {

            LoadQuestionTypes();
            txtFileNumber.Text = PatientService.SuggestFileNumber();
            
            if (Request.QueryString["action"] == "edit")
                LoadPatient();
        }
    }

    private void LoadQuestionTypes() {
        divQuestionArea.Visible = false;

        ddlQuestionTypes.Items.Clear();
        ddlQuestionTypes.Items.Add(new ListItem("---", "-1"));
        ddlQuestionTypes.DataSource = QuestionService.GetQuestionTypes();
        ddlQuestionTypes.DataBind();
    }

    private void LoadQuestions() {
        if (ddlQuestionTypes.SelectedValue == "-1") {
            divQuestionArea.Visible = false;
            return;
        }

        divQuestionArea.Visible = true;

        rQuestions.DataSource = QuestionService.GetQuestionsByType(Convert.ToInt32(ddlQuestionTypes.SelectedValue));
        rQuestions.DataBind();
    }

    private void LoadPatient() {

        int patientId = -1;
        string q = Request.QueryString["id"];
        if (!Int32.TryParse(q, out patientId)) {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("IdNotFoundMessage").ToString());
            return;
        }

        Mani.Patient.Business.Domain.Entity.Patient p = PatientService.GetPatientById(patientId);
        txtPatientName.Text = p.PatientName;
        txtNationalCode.Text = p.NationalCode;

        if ( p.IdNumber.HasValue )
            txtIDNumber.Text = p.IdNumber.ToString();
        
        if ( p.BirthDate.HasValue )
            txtBirthDate.Text = MyPersianDate.DateTimeToPersian(p.BirthDate);

        txtFatherName.Text = p.FatherName;
        txtTel.Text = p.Tel;
        txtEmailAddress.Text = p.EmailAddress;
        txtFamiliarity.Text = p.Familiarity;
        txtDescription.Text = p.Description;
        txtAddress.Text = p.Address;
        cbVIP.Checked = p.VIP;
        txtFileNumber.Text = p.File.FileNumber;
        divQuestionType.Visible = false;
        divQuestionArea.Visible = true;
        rQuestions.DataSource = p.File.Answers;
        rQuestions.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e) {

        if (divQuestionType.Visible && ddlQuestionTypes.SelectedValue == "-1") {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("ChooseFileTypeMessage").ToString());
            return;
        }

        Mani.Patient.Business.Domain.Entity.Patient p = null;

        string action = Request.QueryString["action"];

        if (action == "new") {
            p = new Mani.Patient.Business.Domain.Entity.Patient();
            p.SubmitDate = DateTime.Now;
            p.File = CreateFile(p);
        }
        else if (action == "edit") {
            int patientId = -1;
            string q = Request.QueryString["id"];
            if (!Int32.TryParse(q, out patientId)) {
                UIHelper.ClientAlert(this.Page, GetLocalResourceObject("IdNotFoundMessage").ToString());
                return;
            }

            p = PatientService.GetPatientById(patientId);
            p.File = UpdateFile(p);
        }
        else {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("incorrectParamMessage").ToString());
            return;
        }

        p.PatientName = txtPatientName.Text;
        p.NationalCode = txtNationalCode.Text;

        if (!String.IsNullOrEmpty(txtIDNumber.Text))
            p.IdNumber = Convert.ToInt32(txtIDNumber.Text);
        else
            p.IdNumber = null;

        if (!String.IsNullOrEmpty(txtBirthDate.Text))
            p.BirthDate = MyPersianDate.PersianToDateTime(txtBirthDate.Text);
        else
            p.BirthDate = null;

        p.FatherName = txtFatherName.Text;
        p.Tel = txtTel.Text;
        p.EmailAddress = txtEmailAddress.Text;
        p.Familiarity = txtFamiliarity.Text;
        p.Description = txtDescription.Text;
        p.Address = txtAddress.Text;
        p.VIP = cbVIP.Checked;
        p.Picture = null;
        PatientService.SavePatient(p);
        UIHelper.ClientAlert(this.Page, GetLocalResourceObject("successMessage").ToString());

        if ( cbImmediateVisit.Checked )
            UIHelper.ClientRedirect(this.Page, String.Format("visitd.aspx?Id={0}", p.Id));
        else if (action == "new")
            UIHelper.ClientRedirect(this.Page, "PatientInfo.aspx?action=new");
    }

    private File CreateFile(Patient p) {
        File f = new File();
        f.FileNumber = txtFileNumber.Text;
        f.CreateDate = DateTime.Now;
        f.Patient = p;
        f.Answers = new List<Answer>();

        foreach ( RepeaterItem item in rQuestions.Items) {

            Label lblQuestionId = (Label)item.FindControl("lblRepeaterId");
            TextBox txtAnswerDesc = (TextBox)item.FindControl("txtAnswer");
            
            Answer a = new Answer();
            a.File = f;
            a.Question = QuestionService.GetQuestion(Convert.ToInt32(lblQuestionId.Text));
            a.AnswerDesc = txtAnswerDesc.Text;
            f.Answers.Add(a);
        }

        return f;
    }

    private File UpdateFile(Patient p) {
        p.File.FileNumber = txtFileNumber.Text;


        foreach (RepeaterItem item in rQuestions.Items) {

            Label lblAnswerId = (Label)item.FindControl("lblRepeaterId");
            TextBox txtAnswerDesc = (TextBox)item.FindControl("txtAnswer");

            for (int i = 0; i < p.File.Answers.Count; i++) {

                if ( p.File.Answers[i].Id == Convert.ToInt32( lblAnswerId.Text ) )
                    p.File.Answers[i].AnswerDesc = txtAnswerDesc.Text;
            }
        }

        return p.File;
    }

    protected void ddlQuestionTypes_SelectedIndexChanged(object sender, EventArgs e) {
        LoadQuestions();
        btnSave.Focus();
    }
}
